package ttcamera.common;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

public class TTCameraGetHostIPV4 {

	private Context mContext;

	public TTCameraGetHostIPV4(Context context) {
		mContext = context;
	}

	public String getHostIPV4() {
		WifiManager wifiManager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		if (wifiInfo.getBSSID() != null) {
			return convertDecToIPV4(wifiInfo.getIpAddress());
		}
		return null;
	}

	private String convertDecToIPV4(int dec) {
		return convertBinToIPV4(convertDecToBin(dec));
	}

	private String convertDecToBin(int dec) {
		String bin = Integer.toBinaryString(dec);
		return bin;
	}

	private String convertBinToIPV4(String bin) {
		String result = "";
		String[] ip = new String[4];
		for (int i = 0; i < 32 - bin.length(); i++) {
			bin = "0" + bin;
		}
		for (int i = 0; i < 4; i++) {
			for (int j = 0; j < 8; j++) {
				ip[i] += bin.toCharArray()[i * 8 + j];
			}
		}
		result += Integer.parseInt(ip[3].substring(4, 12), 2) + "."
				+ Integer.parseInt(ip[2].substring(4, 12), 2) + "."
				+ Integer.parseInt(ip[1].substring(4, 12), 2) + ".1";
		// Integer.parseInt(ip[0].substring(4, 12), 2);
		return result;
	}

	public String getSubnetMask() {
		WifiManager wifiManager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		if (wifiInfo.getBSSID() != null) {
			return convertDecToSubnetMask(wifiInfo.getIpAddress());
		}
		return null;
	}

	private String convertDecToSubnetMask(int dec) {
		return convertBinToSubnetMask(convertDecToBin(dec));
	}

	private String convertBinToSubnetMask(String bin) {
		String result = "";
		String[] ip = new String[4];
		for (int i = 0; i < 32 - bin.length(); i++) {
			bin = "0" + bin;
		}
		for (int i = 0; i < 4; i++) {
			for (int j = 0; j < 8; j++) {
				ip[i] += bin.toCharArray()[i * 8 + j];
			}
		}
		result += Integer.parseInt(ip[3].substring(4, 12), 2) + "."
				+ Integer.parseInt(ip[2].substring(4, 12), 2) + "."
				+ Integer.parseInt(ip[1].substring(4, 12), 2);// + ".1";
		// Integer.parseInt(ip[0].substring(4, 12), 2);
		return result;
	}
}
